package com.yami.shop.admin.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.base.Objects;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yami.shop.bean.app.dto.UserDeductionFundDto;
import com.yami.shop.bean.dto.RefundMoneyDistributionDto;
import com.yami.shop.bean.dto.RefundOrderFundTypeDto;
import com.yami.shop.bean.enums.UserFundDetailEnum;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.OrderParam;
import com.yami.shop.bean.param.OrderRefundParam;
import com.yami.shop.bean.param.RefundApprovalParam;
import com.yami.shop.bean.param.UserCashOutApprovalParam;
import com.yami.shop.bean.vo.OrderRefundVo;
import com.yami.shop.bean.vo.RefundOrderItemVo;
import com.yami.shop.bean.vo.RefundOrderVo;
import com.yami.shop.bean.vo.UserFundDetailVo;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.OrderItemMapper;
import com.yami.shop.dao.OrderSettlementMapper;
import com.yami.shop.dao.ProductMapper;
import com.yami.shop.dao.SkuMapper;
import com.yami.shop.payment.WeChatPayment;
import com.yami.shop.payment.dto.GetJsapiServiceDto;
import com.yami.shop.payment.dto.PayParamDto;
import com.yami.shop.payment.dto.RefundParam;
import com.yami.shop.payment.dto.TransferAccountsDto;
import com.yami.shop.security.admin.util.SecurityUtils;
import com.yami.shop.service.*;
import jakarta.validation.Valid;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.StreamInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order/refund")
public class OrderRefundController {

    @Autowired
    private OrderRefundService orderRefundService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private WeChatPayment weChatPayment;

    @Autowired
    private OrderSettlementMapper orderSettlementMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductService productService;
    @Autowired
    private SkuService skuService;

    /**
     * 分页获取
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('order:refund:page')")
    public ServerResponseEntity<IPage<Order>> page(PageParam page, OrderRefundParam orderRefund) {
        Long shopId = SecurityUtils.getSysUser().getShopId();
        LambdaQueryWrapper<OrderRefund> userFundDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();

        userFundDetailLambdaQueryWrapper.eq(orderRefund.getStatus()!= null,OrderRefund::getRefundSts,orderRefund.getStatus());
        userFundDetailLambdaQueryWrapper.eq(StringUtils.isNotBlank(orderRefund.getOrderNumber()),OrderRefund::getOrderNumber,orderRefund.getOrderNumber());
        userFundDetailLambdaQueryWrapper.between(orderRefund.getStartTime()!=null && orderRefund.getEndTime()!=null,OrderRefund::getApplyTime,orderRefund.getStartTime(),orderRefund.getEndTime());


        userFundDetailLambdaQueryWrapper.orderByDesc(OrderRefund::getApplyTime);
        PageParam page1 = orderRefundService.page(page,userFundDetailLambdaQueryWrapper);

        List<OrderRefund> records = page1.getRecords();

        List<OrderRefundVo> list1=new ArrayList<>();
        for (OrderRefund detail:records){
            OrderRefundVo vo=new OrderRefundVo();
            BeanUtil.copyProperties(detail,vo);

            User byId = userService.getById(detail.getUserId());
            if(byId != null){
                vo.setUserName(byId.getNickName());
            }

            OrderItem byId1 = orderItemService.getById(detail.getOrderItemId());
            if(byId1 != null){
                vo.setProdName(byId1.getProdName());
                vo.setPic(byId1.getPic());
                vo.setSkuName(byId1.getSkuName());
                vo.setProdCount(byId1.getProdCount());
            }

            list1.add(vo);
        }

        page1.setRecords(list1);
        return ServerResponseEntity.success(page1);
    }

    /**
     * 提现审批
     *
     * @param param 用户地址管理
     * @return 是否新增成功
     */
    @SysLog("退款审批")
    @PostMapping("/approval")
    @PreAuthorize("@pms.hasPermission('order:refund:approval')")
    @Transactional
    public ServerResponseEntity<Boolean> approval(@RequestBody @Valid RefundApprovalParam param) {
        Long userId = SecurityUtils.getSysUser().getUserId();

        OrderRefund byId = orderRefundService.getById(param.getId());
        if (byId == null) {
            return ServerResponseEntity.showFailMsg("退款记录不存在");
        }

        if (byId.getRefundSts() != 1) {
            return ServerResponseEntity.showFailMsg("退款记录 不能重复审核");
        }

        Order byId2 = orderService.getById(byId.getOrderId());
        if(byId2 == null){
            return ServerResponseEntity.showFailMsg("查询订单为空");
        }

        if (StringUtils.equals(param.getResult(), "0")) {
            //通过
            if(param.getRefundAmount() == null){
                return ServerResponseEntity.showFailMsg("退款金额不能为空");
            }

            //本次退款总金额
            Double add = Arith.add(param.getRefundAmount().getActualityPayMoney(), param.getRefundAmount().getDistributionBonus());

            if(byId.getRefundAmount().compareTo(new BigDecimal(String.valueOf(add))) < 0){
                return ServerResponseEntity.showFailMsg("退款金额不能超过订单实际支付金额");
            }

            OrderRefund refund=new OrderRefund();
            refund.setRefundId(byId.getRefundId());

            refund.setRefundSts(2);//同意

            refund.setRefundAmount(new BigDecimal(String.valueOf(add)));

            refund.setHandelTime(new Date());

            orderRefundService.updateById(refund);

            /**
             * 验证是否订单数量全部退款后,再退款
             */
            OrderItem byId1 = orderItemService.getById(byId.getOrderItemId());
            List<OrderRefund> list1 = orderRefundService.lambdaQuery()
                    .eq(OrderRefund::getOrderNumber, byId.getOrderNumber())
                    .eq(OrderRefund::getOrderItemId, byId.getOrderItemId())
                    .in(OrderRefund::getReturnMoneySts, Arrays.asList(1))
                    .list();
            int sum = list1.stream().mapToInt(r -> r.getGoodsNum()).sum();
            //订单商品数量已经全部退款
            if(byId1.getProdCount() <= sum){
                //下单数量 不能 小于已申请退款数量加本次申请退款数量
                throw new YamiShopBindException("订单商品数量已经全部退款");
            }

            //恢复库存
            List<OrderItem> allOrderItems = Arrays.asList(byId1);

            Map<Long, Integer> prodCollect = new HashMap<>(16);
            Map<Long, Integer> skuCollect = new HashMap<>(16);

            allOrderItems.stream().collect(Collectors.groupingBy(OrderItem::getProdId)).forEach((prodId, orderItems) -> {
                int prodTotalNum = orderItems.stream().mapToInt(OrderItem::getProdCount).sum();
                prodCollect.put(prodId, prodTotalNum);
            });
            productMapper.returnStock(prodCollect);

            allOrderItems.stream().collect(Collectors.groupingBy(OrderItem::getSkuId)).forEach((skuId, orderItems) -> {
                int prodTotalNum = orderItems.stream().mapToInt(OrderItem::getProdCount).sum();
                skuCollect.put(skuId, prodTotalNum);
            });
            skuMapper.returnStock(skuCollect);

            // 清除缓存
            for (OrderItem orderItem : allOrderItems) {
                productService.removeProductCacheByProdId(orderItem.getProdId());
                skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId());
            }

            /*List<OrderSettlement> settlements = orderSettlementMapper.getSettlementsByPayNo(byId.getFlowTradeNo());
            // 应支付的总金额
            double payAmount = 0.0;
            for (OrderSettlement orderSettlement : settlements) {
                payAmount = Arith.add(payAmount, orderSettlement.getPayAmount());
            }*/

            if(param.getRefundAmount().getActualityPayMoney() != null && param.getRefundAmount().getActualityPayMoney() > 0D){
                if(byId.getPayType() == 1){
                    //微信
                    GetJsapiServiceDto getJsapiServiceDto = new GetJsapiServiceDto();
                    getJsapiServiceDto.setWechatpayMchid(WeChatPayment.wechatpayMchid);
                    getJsapiServiceDto.setWechatpayMchserialno(WeChatPayment.wechatpayMchserialno);
                    getJsapiServiceDto.setWechatpayPrivatekey(WeChatPayment.wechatpayPrivatekey);
                    getJsapiServiceDto.setWechatpayApiv3key(WeChatPayment.wechatpayApiv3key);

                    getJsapiServiceDto.setWechatpayAppid(WeChatPayment.wechatpayAppid);
                    getJsapiServiceDto.setWechatpayAppsecret(WeChatPayment.wechatpayAppsecret);

                    RefundParam param1=new RefundParam();
                    param1.setOutTradeNo(byId.getFlowTradeNo());
                    param1.setTotal(String.valueOf(Arith.sub(byId2.getActualTotal(),byId2.getPlatformDeductionAmount())));//实际微信支付总金额
                    param1.setRefund(String.valueOf(param.getRefundAmount().getActualityPayMoney()));//本次退款金额
                    param1.setBody("退款");
                    param1.setOutRefundNo(byId.getOutRefundNo());

                    weChatPayment.refundOrder(param1,getJsapiServiceDto);
                }else if(byId.getPayType() == 2){
                    //支付宝
                }
            }
            //退回各种抵扣金额
            Gson gson=new Gson();
            Type listType = new TypeToken<List<UserDeductionFundDto>>() {}.getType();

            List<UserDeductionFundDto> list2 =new ArrayList<>();
            RefundOrderFundTypeDto dto1=new RefundOrderFundTypeDto();

            List<UserDeductionFundDto> personList = gson.fromJson(byId2.getPlatformDeductionDetailsJson(), listType);
            for (UserDeductionFundDto dto:personList){
                if (StringUtil.equals(dto.getFundField(),"distribution_bonus")){
                    if(param.getRefundAmount().getDistributionBonus() != null && param.getRefundAmount().getDistributionBonus() > 0D){
                        dto.setDeductionMoney(new BigDecimal(String.valueOf(param.getRefundAmount().getDistributionBonus())));

                        dto1.setDistributionBonus(param.getRefundAmount().getDistributionBonus());

                        list2.add(dto);
                    }
                }//...追加其他退回金额
            }

            //退回资金
            userService.userDeductionFundReturn(list2,byId2.getOrderNumber());

            //本次退款是否存在移动支付退款,如果没有,就是本次退回的全是平台资金
            boolean b = param.getRefundAmount().getActualityPayMoney() != null && param.getRefundAmount().getActualityPayMoney() > 0D;

            //保存已经退回的资金
            OrderRefund refund1=new OrderRefund();
            refund1.setRefundId(byId.getRefundId());
            refund1.setActualityReturnMoneyJson(gson.toJson(dto1));

            if(!b){
                refund1.setReturnMoneySts(1);//退款成功
            }

            orderRefundService.updateById(refund1);

        } else if (StringUtils.equals(param.getResult(), "1")) {
            //驳回
            if (StringUtils.isBlank(param.getRejectReason())) {
                return ServerResponseEntity.showFailMsg("驳回必须填写原因");
            }
            OrderRefund refund=new OrderRefund();
            refund.setRefundId(byId.getRefundId());

            refund.setRefundSts(3);//不同意
            refund.setRejectMessage(param.getRejectReason());
            refund.setHandelTime(new Date());
            orderRefundService.updateById(refund);
        }

        return ServerResponseEntity.success(true);
    }

    /**
     * 退款审批前的退款统计
     * @param orderId
     * @return
     */
    @GetMapping("/refundOrderInfo")
    public ServerResponseEntity<Order> refundOrderInfo(String orderId,String refundId ) {
        Order order = orderService.getById(orderId);
        if(order == null){
            return ServerResponseEntity.showFailMsg("订单不存在");
        }

        RefundOrderVo vo=new RefundOrderVo();
        BeanUtil.copyProperties(order,vo);

        Gson gson=new Gson();
        Type listType = new TypeToken<List<UserDeductionFundDto>>() {}.getType();

        //Type RefundOrderFundTypeDtoType = new TypeToken<List<RefundOrderFundTypeDto>>() {}.getType();

        //订单资金详情
        RefundOrderFundTypeDto refundOrderFundTypeDto = new RefundOrderFundTypeDto();
        if(order.getPlatformDeductionAmount() != null && order.getPlatformDeductionAmount() > 0D){
            //设置实际支付金额
            refundOrderFundTypeDto.setActualityPayMoney(Arith.sub(order.getActualTotal(),order.getPlatformDeductionAmount()));

            //查找distributionBonus字段的抵扣金额
            List<UserDeductionFundDto> personList = gson.fromJson(order.getPlatformDeductionDetailsJson(), listType);
            UserDeductionFundDto dto = personList.stream().filter(d -> StringUtil.equals(d.getFundField(), "distribution_bonus")).findFirst().orElse(null);
            if(dto != null){
                refundOrderFundTypeDto.setDistributionBonus(dto.getDeductionMoney().doubleValue());
            }

            //...继续查找其他抵扣资金类型实际抵扣了多少
        }else{
            //设置实际支付金额
            refundOrderFundTypeDto.setActualityPayMoney(order.getActualTotal());
            refundOrderFundTypeDto.setDistributionBonus(0D);
        }
        vo.setFundDetailed(refundOrderFundTypeDto);

        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(order.getOrderNumber());
        List<RefundOrderItemVo> listvo=new ArrayList<>();
        for (OrderItem item:orderItems){
            RefundOrderItemVo vo1=new RefundOrderItemVo();
            BeanUtil.copyProperties(item,vo1);

            List<RefundOrderFundTypeDto> list1=new ArrayList<>();
            List<OrderRefund> list = orderRefundService.lambdaQuery()
                    .eq(OrderRefund::getOrderItemId, item.getOrderItemId())
                    .eq(OrderRefund::getReturnMoneySts, 1)//退款成功的
                    .list();
            for(OrderRefund refund:list){
                RefundOrderFundTypeDto refundOrderFundTypeDto1 = gson.fromJson(refund.getActualityReturnMoneyJson(), RefundOrderFundTypeDto.class);
                if(refundOrderFundTypeDto1 != null){
                    list1.add(refundOrderFundTypeDto1);
                }
            }
            //订单子表关联已退款统计
            RefundOrderFundTypeDto refundOrderFundTypeDto1 = new RefundOrderFundTypeDto();

            //实际支付退款统计
            double sum = list1.stream().filter(r -> r.getActualityPayMoney() != null && r.getActualityPayMoney() > 0).mapToDouble(r -> r.getActualityPayMoney()).sum();
            refundOrderFundTypeDto1.setActualityPayMoney(sum);

            //distributionBonus资金的退款统计
            double sum1 = list1.stream().filter(r -> r.getDistributionBonus() != null && r.getDistributionBonus() > 0).mapToDouble(r -> r.getDistributionBonus()).sum();
            refundOrderFundTypeDto1.setDistributionBonus(sum1);

            //...其他退款资金的统计

            vo1.setAlreadyRefundStatistics(refundOrderFundTypeDto1);

            listvo.add(vo1);
        }

        vo.setRefundOrderItem(listvo);

        //查询订单已退款数量
        Integer num=orderService.queryOrderAlreadyRefundNumber(order.getOrderId());

        OrderRefund byId = orderRefundService.getById(refundId);
        if(order.getProductNums() == num + byId.getGoodsNum()){
            //本次审批假如退款完成,则订单全部退款完成
            vo.setAllRefund(true);
        }else{
            vo.setAllRefund(false);
        }

        //订单所有已退款资金统计
        RefundOrderFundTypeDto orderRefundFundTypeDto = new RefundOrderFundTypeDto();
        //实际支付退款统计
        double sum = listvo.stream().map(r -> r.getAlreadyRefundStatistics()).filter(r -> r.getActualityPayMoney() != null && r.getActualityPayMoney() > 0).mapToDouble(r -> r.getActualityPayMoney()).sum();
        orderRefundFundTypeDto.setActualityPayMoney(sum);

        //distributionBonus资金的退款统计
        double sum1 = listvo.stream().map(r -> r.getAlreadyRefundStatistics()).filter(r -> r.getDistributionBonus() != null && r.getDistributionBonus() > 0).mapToDouble(r -> r.getDistributionBonus()).sum();
        orderRefundFundTypeDto.setDistributionBonus(sum1);

        vo.setAlreadyRefundfundDetailed(orderRefundFundTypeDto);

        return ServerResponseEntity.success(vo);
    }

    /**
     * 分配退款金额
     * @param refundId
     * @return
     */
    @GetMapping("/calculateThisTimeRefundMoneyDistribution")
    public ServerResponseEntity<RefundOrderFundTypeDto> calculateThisTimeRefundMoneyDistribution(String refundId ) {
        OrderRefund byId = orderRefundService.getById(refundId);
        if(byId == null){
            return ServerResponseEntity.showFailMsg("查询退款申请为空");
        }
        Order order = orderService.getById(byId.getOrderId());
        if(order == null){
            return ServerResponseEntity.showFailMsg("查询订单为空");
        }
        Gson gson=new Gson();
        Type listType = new TypeToken<List<UserDeductionFundDto>>() {}.getType();
        //查询订单资金详情
        RefundOrderFundTypeDto refundOrderFundTypeDto = new RefundOrderFundTypeDto();
        if(order.getPlatformDeductionAmount() != null && order.getPlatformDeductionAmount() > 0D){
            //设置实际支付金额
            refundOrderFundTypeDto.setActualityPayMoney(Arith.sub(order.getActualTotal(),order.getPlatformDeductionAmount()));

            //查找distributionBonus字段的抵扣金额
            List<UserDeductionFundDto> personList = gson.fromJson(order.getPlatformDeductionDetailsJson(), listType);
            UserDeductionFundDto dto = personList.stream().filter(d -> StringUtil.equals(d.getFundField(), "distribution_bonus")).findFirst().orElse(null);
            if(dto != null){
                refundOrderFundTypeDto.setDistributionBonus(dto.getDeductionMoney().doubleValue());
            }

            //...继续查找其他抵扣资金类型实际抵扣了多少
        }else{
            //设置实际支付金额
            refundOrderFundTypeDto.setActualityPayMoney(order.getActualTotal());
            refundOrderFundTypeDto.setDistributionBonus(0D);
        }

        //查询已退款金额
        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(order.getOrderNumber());
        List<RefundOrderFundTypeDto> list1=new ArrayList<>();
        for (OrderItem item:orderItems){
            List<OrderRefund> list = orderRefundService.lambdaQuery()
                    .eq(OrderRefund::getOrderItemId, item.getOrderItemId())
                    .eq(OrderRefund::getReturnMoneySts, 1)//退款成功的
                    .list();
            for(OrderRefund refund:list){
                RefundOrderFundTypeDto refundOrderFundTypeDto1 = gson.fromJson(refund.getActualityReturnMoneyJson(), RefundOrderFundTypeDto.class);
                if(refundOrderFundTypeDto1 != null){
                    list1.add(refundOrderFundTypeDto1);
                }
            }
        }

        //订单子表关联已退款统计
        RefundOrderFundTypeDto refundOrderFundTypeDto1 = new RefundOrderFundTypeDto();

        //实际支付退款统计
        double sum = list1.stream().filter(r -> r.getActualityPayMoney() != null && r.getActualityPayMoney() > 0).mapToDouble(r -> r.getActualityPayMoney()).sum();
        refundOrderFundTypeDto1.setActualityPayMoney(sum);

        //distributionBonus资金的退款统计
        double sum1 = list1.stream().filter(r -> r.getDistributionBonus() != null && r.getDistributionBonus() > 0).mapToDouble(r -> r.getDistributionBonus()).sum();
        refundOrderFundTypeDto1.setDistributionBonus(sum1);

        //每项资金剩余多少未退回
        RefundOrderFundTypeDto refundOrderFundTypeDto2 = new RefundOrderFundTypeDto();
        refundOrderFundTypeDto2.setActualityPayMoney(Arith.sub(refundOrderFundTypeDto.getActualityPayMoney(),refundOrderFundTypeDto1.getActualityPayMoney()));
        refundOrderFundTypeDto2.setDistributionBonus(Arith.sub(refundOrderFundTypeDto.getDistributionBonus(),refundOrderFundTypeDto1.getDistributionBonus()));

        //查询订单已退款数量
        Integer num=orderService.queryOrderAlreadyRefundNumber(order.getOrderId());
        if(order.getProductNums() == num + byId.getGoodsNum()){
            //本次审批假如退款完成,则订单全部退款完成
            //说明本次退款是本订单的最后一次退款,所有商品都退完了
            return ServerResponseEntity.success(refundOrderFundTypeDto2);//退回剩余全部
        }

        RefundMoneyDistributionDto refundMoneyDistributionDto = new RefundMoneyDistributionDto();
        refundMoneyDistributionDto.setFundType("actualityPayMoney");
        refundMoneyDistributionDto.setMoney(refundOrderFundTypeDto2.getActualityPayMoney());

        RefundMoneyDistributionDto refundMoneyDistributionDto1 = new RefundMoneyDistributionDto();
        refundMoneyDistributionDto1.setFundType("distributionBonus");
        refundMoneyDistributionDto1.setMoney(refundOrderFundTypeDto2.getDistributionBonus());

        List<RefundMoneyDistributionDto> list=new ArrayList<>();
        list.add(refundMoneyDistributionDto);
        list.add(refundMoneyDistributionDto1);

        //计算退款金额,分布在未退款资金上
        List<RefundMoneyDistributionDto> list2=allocationMoney(list,byId.getRefundAmount());

        if(list2 == null){
            //已经全部退款,无可分配金额
            RefundOrderFundTypeDto refundOrderFundTypeDto3 = new RefundOrderFundTypeDto();
            refundOrderFundTypeDto3.setDistributionBonus(0D);
            refundOrderFundTypeDto3.setActualityPayMoney(0D);
            return ServerResponseEntity.success(refundOrderFundTypeDto3);
        }

        //本次退款的退款资金分配
        RefundOrderFundTypeDto refundOrderFundTypeDto3 = new RefundOrderFundTypeDto();
        RefundMoneyDistributionDto distributionDto = list2.stream().filter(d -> StringUtil.equals(d.getFundType(), "distributionBonus")).findFirst().orElse(null);
        refundOrderFundTypeDto3.setDistributionBonus(distributionDto!=null?distributionDto.getMoney():0D);

        RefundMoneyDistributionDto distributionDto1 = list2.stream().filter(d -> StringUtil.equals(d.getFundType(), "actualityPayMoney")).findFirst().orElse(null);
        refundOrderFundTypeDto3.setActualityPayMoney(distributionDto1!=null?distributionDto1.getMoney():0D);

        return ServerResponseEntity.success(refundOrderFundTypeDto3);
    }

    public List<RefundMoneyDistributionDto> allocationMoney(List<RefundMoneyDistributionDto> list, BigDecimal refundAmount) {
        //先退会分销奖金中的资金
        List<String> strings = Arrays.asList("distributionBonus", "actualityPayMoney");
        List<RefundMoneyDistributionDto> collect = list.stream()
                .sorted(Comparator.comparingInt(item ->
                        strings.indexOf(item.getFundType())))
                .collect(Collectors.toList());

        List<RefundMoneyDistributionDto> list1=new ArrayList<>();
        BigDecimal notAllocationMoney=refundAmount;

        for(RefundMoneyDistributionDto dto:collect){
            BigDecimal bigDecimal = new BigDecimal(String.valueOf(dto.getMoney()));
            //if(dto.getMoney() >= notAllocationMoney){
            if(bigDecimal.compareTo(notAllocationMoney) >= 0){
                //当前资金大于需退回资金
                RefundMoneyDistributionDto distributionDto=new RefundMoneyDistributionDto();
                distributionDto.setFundType(dto.getFundType());
                distributionDto.setMoney(notAllocationMoney.doubleValue());
                list1.add(distributionDto);
                return list1;
            }else {
                //当前资金小于需退回资金,当前资金不够扣
                RefundMoneyDistributionDto distributionDto=new RefundMoneyDistributionDto();
                distributionDto.setFundType(dto.getFundType());
                distributionDto.setMoney(dto.getMoney());
                list1.add(distributionDto);

                //notAllocationMoney = notAllocationMoney - dto.getMoney();
                notAllocationMoney = notAllocationMoney.subtract(bigDecimal);
            }
        }
        //循环完还没分配完资金,有错误了
        return null;
    }

    /*public static void main(String[] args) {
        RefundMoneyDistributionDto refundMoneyDistributionDto1 = new RefundMoneyDistributionDto();
        refundMoneyDistributionDto1.setFundType("distributionBonus");
        refundMoneyDistributionDto1.setMoney(2D);


        RefundMoneyDistributionDto refundMoneyDistributionDto2 = new RefundMoneyDistributionDto();
        refundMoneyDistributionDto2.setFundType("distributionBonus1");
        refundMoneyDistributionDto2.setMoney(2D);


        RefundMoneyDistributionDto refundMoneyDistributionDto = new RefundMoneyDistributionDto();
        refundMoneyDistributionDto.setFundType("actualityPayMoney");
        refundMoneyDistributionDto.setMoney(1D);



        List<RefundMoneyDistributionDto> list=new ArrayList<>();
        list.add(refundMoneyDistributionDto);
        list.add(refundMoneyDistributionDto1);
        list.add(refundMoneyDistributionDto2);

        OrderRefundController controller=new OrderRefundController();
        List<RefundMoneyDistributionDto> refundMoneyDistributionDtos = controller.allocationMoney(list, new BigDecimal("3"));
        System.out.println(refundMoneyDistributionDtos);
    }*/
}
